import os.path
import re
import urllib

def basename(url):
    head, sep, tail = url.partition("://")
    if head == "file":
        base_ = os.path.basename(tail).replace("+", " ")
        base = urllib.unquote(base_)
        return base
    else:
        return url


def msecToStr(msec):
    hrs = msec // 3600e3
    rem = msec % 3600e3
    min = rem // 60e3
    rem = rem % 60e3
    sec = rem // 1e3
    if hrs == 0: return "%02.0f:%02.0f" % (min, sec)
    else: return "%02.0f:%02.0f:%02.0f" % (hrs, min, sec)


def retag(format, id, string):
    """ batchRetag(format, idIter):
    retag given files in mlib using format. Format must be a pattern (regexp?)
    with some of the following wildcards:
    
    %n - Track Number
    %t - Title
    %a - Artist
    %l - Album

    idIter must be a iterator returning tuples of the form (id, string) where
    id is the mlib id of the song and string is the string to extract tags from.
    """

    modifiers = re.findall(r"%[ntal]", format)
    format = re.sub(r"%[tal]", r"(.+)", format)
    if "%n" in modifiers:
        format = re.sub(r"%n", r"(\d+)", format)
    match = re.match(format, string)
    for key, val in zip(modifiers, match.groups()):
        print key, ":", val


def squeeze(info, format):
    """squeezes the info using format to do so ;).
    info is a dictionary containing information from a mlib entry as those
    found invoking xmmsclient.XMMS.medialib_get_info().
    format is a regexp with the format that info will have. You can use these
    wildcards:
        %a - Artist
        %l - Album
        %n - Track number
        %t - Title
        %d - duration
    if title is None it returns the media basename or url instead.
    """
    for key in "title", "album", "artist":
        try: exec '%s = info["%s"]' % (key, key)
        except: exec '%s = ""' % key
    try: tracknr = "%02d" % info["tracknr"]
    except: tracknr = ""
    try: duration = msecToStr(info["duration"])
    except: duration = "??:??"
    if not title: title = basename(info["url"])
    juice = format.replace("%t", title)
    juice = juice.replace("%l", album)
    juice = juice.replace("%a", artist)
    juice = juice.replace("%n", tracknr)
    juice = juice.replace("%d", duration)
    return juice


if __name__ == "__main__":
    format = r"%a - %n - %t.mp3"
    string = "Opeth - 03 - Nectar.mp3"
    id = 23
    batchRetag(format, id, string)
